//package com.dong.controller;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.dong.beans.staticBeaned;
//import com.dong.mqtt.EmqClient;
//import com.dong.mqtt.EmqMsgProcess;
//import com.dong.mybatis.entity.Zone1;
//import com.dong.mybatis.service.impl.Zone1ServiceImpl;
//
//import jakarta.annotation.Resource;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.time.LocalDateTime;
//
//@RequestMapping("mqtt")
//@RestController
//@Slf4j
//public class MqttController {
//@Resource
//Zone1ServiceImpl zone1Service;
//
//    @Autowired
//    EmqClient emqClient;
//    @PostMapping("postmsg")
//    public String postMes(String topic, String message) {
//        log.info("接收到❤️控制数据{}来自主题{}",message,topic);
////        emqMsgProcess.
//       emqClient.publish(topic,message);
//
//        return null;
//    }
//
//
//}
//




package com.dong.controller;

import com.dong.service.tcpservice;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

@RequestMapping("mqtt")
@RestController
@Slf4j
public class MqttController {

    // 保存所有板子的连接（key = 板子IP）
//    private static final ConcurrentHashMap<String, Socket> deviceMap = new ConcurrentHashMap<>();

    /**
     * 启动 TCP 服务端，等待板子连接
     */


    /**
     * 监听板子发来的消息
     */


    /**
     * HTTP 接口：接收控制消息并转发给板子
     */
    @PostMapping("postmsg")
    public String postMes(String topic, String message) {
        log.info("🌐 接收到 HTTP 控制数据 [{}] 来自主题 [{}]", message, topic);

        String zoneIdAddress = null;
        if ("node1".equals(topic)) {
            zoneIdAddress = "192.168.1.103";
        } else if ("node2".equals(topic)) {
            zoneIdAddress = "192.168.1.104";
        } else if ("node3".equals(topic)) {
            zoneIdAddress = "192.168.1.105";
        } else if ("zone".equals(topic)) {
            zoneIdAddress = "192.168.1.102";
        }

        if (zoneIdAddress == null) {
            return "未知的 topic: " + topic;
        }

        Socket socket = tcpservice.clientSockets.get(zoneIdAddress);
        if (socket == null || socket.isClosed()) {
            log.warn("⚠️ 设备 {} 未连接", zoneIdAddress);
            return "设备未连接: " + zoneIdAddress;
        }

        try {
            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true
            );
            out.println(message);
            log.info("✅ 已发送数据给 [{}], 数据: {}", zoneIdAddress, message);
            return "发送成功: " + message;
        } catch (IOException e) {
            log.error("❌ 发送失败", e);
            return "发送失败: " + e.getMessage();
        }
    }
}








////
////package com.dong.controller;
////
////import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
////import com.dong.beans.staticBeaned;
////import com.dong.mqtt.EmqClient;
////import com.dong.mqtt.EmqMsgProcess;
////import com.dong.mybatis.entity.Zone1;
////import com.dong.mybatis.service.impl.Zone1ServiceImpl;
////
////import jakarta.annotation.Resource;
////import lombok.extern.slf4j.Slf4j;
////import org.springframework.beans.factory.annotation.Autowired;
////import org.springframework.stereotype.Controller;
////import org.springframework.web.bind.annotation.GetMapping;
////import org.springframework.web.bind.annotation.PostMapping;
////import org.springframework.web.bind.annotation.RequestMapping;
////import org.springframework.web.bind.annotation.RestController;
////
////import java.io.*;
////import java.net.Socket;
////import java.time.LocalDateTime;
////
////@RequestMapping("mqtt")
////@RestController
////@Slf4j
////public class MqttController {
////    @Resource
////    Zone1ServiceImpl zone1Service;
////
////    @Autowired
////    EmqClient emqClient;
////    @PostMapping("postmsg")
////    public String postMes(String topic, String message) {
////        log.info("接收到❤️控制数据{}来自主题{}",message,topic);
//////        emqMsgProcess.
//////        emqClient.publish(topic,message);
//////        String topic="zone1";
////        String zoneIdAddress=null;
////        if(topic.equals("zone1")){
////            zoneIdAddress="192.168.1.103";
////        }
////        else if(topic.equals("zone2")){
////            zoneIdAddress="192.168.1.104";
////        }
////        else if(topic.equals("zone3")){
////            zoneIdAddress="192.168.1.105";
////        }
////
////        {
////            try (
////                    // 连接到服务器 (IP + 端口)
////                    Socket socket = new Socket(zoneIdAddress, 8889);
////                    // 输出流：发送数据
////                    PrintWriter out = new PrintWriter(
////                            new OutputStreamWriter(socket.getOutputStream(), "UTF-8"),
////                            true
////                    );
////                    // 输入流：接收服务器回信
////                    BufferedReader in = new BufferedReader(
////                            new InputStreamReader(socket.getInputStream(), "UTF-8")
////                    )
////            ) {
////                // 发送字符串
////                out.println(message);
////                log.info("❤️❤️发送数据给{}成功,数据是{}",zoneIdAddress,message);
////
//////                // 发送数字（字符串形式，服务端会再 parseInt）
//////                out.println("12345");
////
////                // 等待服务器回复
//////                String response = in.readLine();
//////                System.out.println("服务器回复：" + response);
////
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
////        }
////
////        return null;
////    }
////
////
////}


////package com.dong.controller;
////
////import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
////import com.dong.beans.staticBeaned;
////import com.dong.mqtt.EmqClient;
////import com.dong.mqtt.EmqMsgProcess;
////import com.dong.mybatis.entity.Zone1;
////import com.dong.mybatis.service.impl.Zone1ServiceImpl;
////
////import jakarta.annotation.Resource;
////import lombok.extern.slf4j.Slf4j;
////import org.springframework.beans.factory.annotation.Autowired;
////import org.springframework.stereotype.Controller;
////import org.springframework.web.bind.annotation.GetMapping;
////import org.springframework.web.bind.annotation.PostMapping;
////import org.springframework.web.bind.annotation.RequestMapping;
////import org.springframework.web.bind.annotation.RestController;
////
////import java.time.LocalDateTime;
////
////@RequestMapping("mqtt")
////@RestController
////@Slf4j
////public class MqttController {
////@Resource
////Zone1ServiceImpl zone1Service;
////
////    @Autowired
////    EmqClient emqClient;
////    @PostMapping("postmsg")
////    public String postMes(String topic, String message) {
////        log.info("接收到❤️控制数据{}来自主题{}",message,topic);
//////        emqMsgProcess.
////       emqClient.publish(topic,message);
////
////        return null;
////    }
////
////
////}
////
//
//
//
//
//package com.dong.controller;
//
//import jakarta.annotation.PostConstruct;
//import jakarta.annotation.Resource;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import org.springframework.web.bind.annotation.RestController;
//
//import java.io.*;
//import java.net.ServerSocket;
//import java.net.Socket;
//import java.util.concurrent.ConcurrentHashMap;
//
//@RequestMapping("mqtt")
//@RestController
//@Slf4j
//public class MqttController {
//
//    // 保存所有板子的连接（key = 板子IP）
//    private static final ConcurrentHashMap<String, Socket> deviceMap = new ConcurrentHashMap<>();
//
//    /**
//     * 启动 TCP 服务端，等待板子连接
//     */
//    @PostConstruct
//    public void startTcpServer() {
//        new Thread(() -> {
//            try (ServerSocket serverSocket = new ServerSocket(8889)) {
//                log.info("✅ TCP 服务端已启动，监听端口 8889 ...");
//                while (true) {
//                    Socket socket = serverSocket.accept();
//                    String clientIp = socket.getInetAddress().getHostAddress();
//                    deviceMap.put(clientIp, socket);
//                    log.info("板子已连接: {}", clientIp);
//
//                    // 监听板子发来的消息（心跳或业务数据）
//                    new Thread(() -> listenDevice(socket, clientIp)).start();
//                }
//            } catch (IOException e) {
//                log.error("❌ TCP 服务端异常: {}", e.getMessage(), e);
//            }
//        }).start();
//    }
//
//    /**
//     * 监听板子发来的消息
//     */
//    private void listenDevice(Socket socket, String clientIp) {
//        try (BufferedReader in = new BufferedReader(
//                new InputStreamReader(socket.getInputStream(), "UTF-8"))
//        ) {
//            String msg;
//            PrintWriter out = new PrintWriter(
//                    new OutputStreamWriter(socket.getOutputStream(), "UTF-8"),
//                                        true);
//            while ((msg = in.readLine()) != null) {
//                log.info("📥 收到板子 [{}] 的消息: {}", clientIp, msg);
//            }
//        } catch (IOException e) {
//            log.warn("⚠️ 板子 {} 连接断开", clientIp);
//        } finally {
//            deviceMap.remove(clientIp);
//            try {
//                socket.close();
//            } catch (IOException ignored) {}
//        }
//    }
//
//    /**
//     * HTTP 接口：接收控制消息并转发给板子
//     */
//    @PostMapping("postmsg")
//    public String postMes(String topic, String message) {
//        log.info("🌐 接收到 HTTP 控制数据 [{}] 来自主题 [{}]", message, topic);
//
//        String zoneIdAddress = null;
//        if ("zone1".equals(topic)) {
//            zoneIdAddress = "127.0.0.1";
//        } else if ("zone2".equals(topic)) {
//            zoneIdAddress = "192.168.1.104";
//        } else if ("zone3".equals(topic)) {
//            zoneIdAddress = "192.168.1.105";
//        }
//
//        if (zoneIdAddress == null) {
//            return "未知的 topic: " + topic;
//        }
//
//        Socket socket = deviceMap.get(zoneIdAddress);
//        if (socket == null || socket.isClosed()) {
//            log.warn("⚠️ 设备 {} 未连接", zoneIdAddress);
//            return "设备未连接: " + zoneIdAddress;
//        }
//
//        try {
//            PrintWriter out = new PrintWriter(
//                    new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true
//            );
//            out.println(message);
//            log.info("✅ 已发送数据给 [{}], 数据: {}", zoneIdAddress, message);
//            return "发送成功: " + message;
//        } catch (IOException e) {
//            log.error("❌ 发送失败", e);
//            return "发送失败: " + e.getMessage();
//        }
//    }
//}
//
//
//
//
//
//
//
//
//////
//////package com.dong.controller;
//////
//////import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//////import com.dong.beans.staticBeaned;
//////import com.dong.mqtt.EmqClient;
//////import com.dong.mqtt.EmqMsgProcess;
//////import com.dong.mybatis.entity.Zone1;
//////import com.dong.mybatis.service.impl.Zone1ServiceImpl;
//////
//////import jakarta.annotation.Resource;
//////import lombok.extern.slf4j.Slf4j;
//////import org.springframework.beans.factory.annotation.Autowired;
//////import org.springframework.stereotype.Controller;
//////import org.springframework.web.bind.annotation.GetMapping;
//////import org.springframework.web.bind.annotation.PostMapping;
//////import org.springframework.web.bind.annotation.RequestMapping;
//////import org.springframework.web.bind.annotation.RestController;
//////
//////import java.io.*;
//////import java.net.Socket;
//////import java.time.LocalDateTime;
//////
//////@RequestMapping("mqtt")
//////@RestController
//////@Slf4j
//////public class MqttController {
//////    @Resource
//////    Zone1ServiceImpl zone1Service;
//////
//////    @Autowired
//////    EmqClient emqClient;
//////    @PostMapping("postmsg")
//////    public String postMes(String topic, String message) {
//////        log.info("接收到❤️控制数据{}来自主题{}",message,topic);
////////        emqMsgProcess.
////////        emqClient.publish(topic,message);
////////        String topic="zone1";
//////        String zoneIdAddress=null;
//////        if(topic.equals("zone1")){
//////            zoneIdAddress="192.168.1.103";
//////        }
//////        else if(topic.equals("zone2")){
//////            zoneIdAddress="192.168.1.104";
//////        }
//////        else if(topic.equals("zone3")){
//////            zoneIdAddress="192.168.1.105";
//////        }
//////
//////        {
//////            try (
//////                    // 连接到服务器 (IP + 端口)
//////                    Socket socket = new Socket(zoneIdAddress, 8889);
//////                    // 输出流：发送数据
//////                    PrintWriter out = new PrintWriter(
//////                            new OutputStreamWriter(socket.getOutputStream(), "UTF-8"),
//////                            true
//////                    );
//////                    // 输入流：接收服务器回信
//////                    BufferedReader in = new BufferedReader(
//////                            new InputStreamReader(socket.getInputStream(), "UTF-8")
//////                    )
//////            ) {
//////                // 发送字符串
//////                out.println(message);
//////                log.info("❤️❤️发送数据给{}成功,数据是{}",zoneIdAddress,message);
//////
////////                // 发送数字（字符串形式，服务端会再 parseInt）
////////                out.println("12345");
//////
//////                // 等待服务器回复
////////                String response = in.readLine();
////////                System.out.println("服务器回复：" + response);
//////
//////            } catch (IOException e) {
//////                e.printStackTrace();
//////            }
//////        }
//////
//////        return null;
//////    }
//////
//////
//////}
